package com.ruoyi.message.chat;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.message.domain.GroupMessage;
import com.ruoyi.message.domain.GroupUserId;
import com.ruoyi.message.domain.Message;
import com.ruoyi.message.service.IGroupMessageService;
import com.ruoyi.message.service.IGroupUserIdService;
import com.ruoyi.message.service.IMessageService;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyMessageHandler extends TextWebSocketHandler {

    private static Map<String, WebSocketSession> routeTab = new ConcurrentHashMap<>();
    private static final ObjectMapper objectMapper = new ObjectMapper();


    @Override//连接
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String decode = URLDecoder.decode(Objects.requireNonNull(session.getUri()).toString(), Charset.defaultCharset());
        String userId = decode.substring(decode.lastIndexOf("/") + 1);
        routeTab.put(userId, session);//将用户和用户的session存入到路由表中
        redisTemplate.opsForList().rightPush("userList", userId);
        Message message = new Message();
        message.setText(objectMapper.writeValueAsString(redisTemplate.opsForList().range("userList", 0, -1)));
        message.setType("JOIN");
        sendMessage(message);
    }


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private IMessageService messageService;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        Message message1 = objectMapper.readValue(message.getPayload(), Message.class);
        sendMessage(message1);
    }


    @Override//断开连接
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println(2);
    }

    @Autowired
    private IGroupUserIdService groupUserIdService;
    @Autowired
    private IGroupMessageService groupMessageService;

    public void sendMessage(Message message) throws IOException {
        String to = message.getToId();
        System.out.println(message);
        if (to!=null&&to.contains("单")) {
            String toId = to.substring(0, to.indexOf("单"));
            message.setToId(toId);
            message.setTime(new Date());
            messageService.insertMessage(message);
            WebSocketSession webSocketSession = routeTab.get(message.getSenderId());
            WebSocketSession webSocketSession1 = routeTab.get(message.getToId());
            if (!message.getToId().equals(message.getSenderId()) && webSocketSession != null &&
                    webSocketSession.isOpen() && webSocketSession1 != null && webSocketSession1.isOpen()) {
                message.setToId(to);
                webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
                webSocketSession1.sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
            }
            if (!message.getToId().equals(message.getSenderId()) && webSocketSession != null &&
                    webSocketSession.isOpen() && webSocketSession1 == null) {
                message.setToId(to);
                webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
            }
        } else {
            if (to != null && !to.equals("")) {
                GroupUserId groupUserId1 = new GroupUserId();
                groupUserId1.setGroupId(Long.valueOf(to));
                List<GroupUserId> groupUserId = groupUserIdService.selectGroupUserIdList(groupUserId1);
                for (GroupUserId userId : groupUserId) {
                    Message message1 = new Message();
                    message1.setSenderId(String.valueOf(userId.getUserId()));
                    WebSocketSession webSocketSession = routeTab.get(message1.getSenderId());
                    if (webSocketSession != null && webSocketSession.isOpen()) {
                        webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
                    };
                }
                GroupMessage groupMessage = new GroupMessage();
                groupMessage.setMessageType(message.getType());
                groupMessage.setSenderId(Long.valueOf(message.getSenderId()));
                groupMessage.setText(message.getText());
                groupMessage.setGroupId(Long.valueOf(to));
                groupMessage.setMessageTextType(message.getTextType());
                groupMessage.setCreateTime(new Date());
                groupMessage.setSenderName(message.getSenderName());
                groupMessage.setSenderAvatar(message.getSenderAvatar());
                groupMessageService.insertGroupMessage(groupMessage);
            }
        }
    }

}
